package com.icode.core.model.user;

import com.icode.core.model.AbstractEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ZhongGang
 * Date: 15-1-7
 * Time: 下午10:55
 */
@Entity
@Table(name = "user_role")
public class UserRole extends AbstractEntity {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "role_id")
    private Role role;

    public UserRole(User user, Role role) {
        this.user = user;
        this.role = role;
    }

    public User getUser() {
        return user;
    }

    public Role getRole() {
        return role;
    }

    public List<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        Privileges privileges = role.getPrivileges();
        for (Privilege privilege : privileges) {
            String value = privilege.getGrantedAuthority();
            GrantedAuthority authority = new SimpleGrantedAuthority(value);
            authorities.add(authority);
        }
        return authorities;
    }
}
